package com.commerce.authority;

import com.commerce.common.Reminder;
import com.commerce.constant.UserType;
import com.commerce.model.Admin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wyj
 * @Title:
 * @Description:
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Admin admin = (Admin)httpServletRequest.getSession().getAttribute(UserType.ADMINUSET.name());
        if(admin ==null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin/login");
            return false;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Authority authority = handlerMethod.getBeanType().getAnnotation(Authority.class);
        if(authority==null)authority = handlerMethod.getMethod().getAnnotation(Authority.class);
        if(isAuthority(authority,admin)){
           return true;
        }
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin/error/auth");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public boolean isAuthority(Authority authority , Admin admin){
        if(AuthType.ALL.getName().equals(admin.getAuthoritys())){
            return true;
        }
        if(authority == null){
            return true;
        }
        if(admin.getAuthoritys() != null && admin.getAuthoritys().indexOf(authority.toString()) >-1){
            return true;
        }
        return false;
    }
}
